/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package edu.lnu.ums.entities.core;

import edu.lnu.ums.dal.exception.EntityManagerFactoryCreationException;
import edu.lnu.ums.dal.factories.FactoriesCache;
import java.util.ArrayList;
import java.util.List;
import javax.faces.model.SelectItem;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EntityManagerFactory;

@Entity
public class LinkToAnotherDB extends UMSObject {

    public LinkToAnotherDB() {
        
    }


    @Column
    private String pathToDB;

    @Column
    private String userName;

    @Column(name="pass")
    private String password;

    @Column(name="provider")
    private String provider;
    
    public boolean getConnected() {
        return FactoriesCache.getInstance().getFactory(this.getNodeName()) != null;
    }

    public void setConnected(boolean connected) {
        if (connected) {
            try {
                connect();
            } catch (EntityManagerFactoryCreationException ex) {
                ex.printStackTrace();
            }
        } else {
            disconnect();
        }

    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getPathToDB() {
        return pathToDB;
    }

    public void setPathToDB(String pathToDB) {
        this.pathToDB = pathToDB;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

     public String getProvider() {
        return provider;
    }

    public void setProvider(String provider) {
        this.provider = provider;
    }

    public List<SelectItem> getAllProviders(){
        List<String> providers = new ArrayList<String>();
	providers.add("Firebird");
	providers.add("MS SQL");
	return transformCollection(providers);
    }
    
    public void connect() throws EntityManagerFactoryCreationException {
        if (!getConnected()) {
            FactoriesCache.getInstance().addFactory(
                    this.getNodeName(), pathToDB, userName, password, provider);
        }
    }

    public void disconnect() {
        FactoriesCache.getInstance().removeFactory(this.getNodeName());
    }

    public EntityManagerFactory getAnotherDBFactory() {
        return FactoriesCache.getInstance().getFactory(this.getNodeName());
    }

    private List<SelectItem> transformCollection(List<?> list) {
	List<SelectItem> items = new ArrayList<SelectItem>();
	for (Object obj : list) {
		items.add(new SelectItem(obj));
	}
	return items;
    }
}
